package com.runachina.runa;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.common.BaseActivity;
import com.runachina.common.CompanyActivity;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

public class SetDataActivity extends BaseActivity {

    public static EditText nownum, allhot, allflow, alltime;
    public static TextView allhotunit, allflowunit;
    private Button readbtn, setdbtn;
    private TextView sendtitle, sendtext;
    private TextView helptitle, helptext;
    public static TextView rcvtext, rcvbyte;

    private int helpFlag = 1;

    private static byte[] setData = {(byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe, (byte) 0xfe,
            0x68, 0x20,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//表号
            0x00, 0x11, 0x11, 0x16, 0x14, 0x16, (byte) 0xa0, (byte) 0x88, 0x00,
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//累计热量
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//累计冷量
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//累计流量
            (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,//累计时间
            (byte) 0x00, 0x16,
            (byte) 0x00, 0x16};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_setdata);

        set_toolbar("设置数据", "");

        set_leftmenu(SetDataActivity.this);

        init_view();

        hideSendText(sendtitle, sendtext, "GONE");

        inWhichAc = "runa.SetDataActivity";
    }

    private void init_view() {
        nownum = (EditText) findViewById(R.id.nownum);
        allhot = (EditText) findViewById(R.id.allhot);
        allflow = (EditText) findViewById(R.id.allflow);
        alltime = (EditText) findViewById(R.id.alltime);

        readbtn = (Button) findViewById(R.id.readbtn);
        readbtn.setOnClickListener(readbtnFun);
        setdbtn = (Button) findViewById(R.id.setdbtn);
        setdbtn.setOnClickListener(setdbtnFun);

        sendtitle = (TextView) findViewById(R.id.sendtitle);
        sendtext = (TextView) findViewById(R.id.sendtext);
        rcvtext = (TextView) findViewById(R.id.rcvtext);
        rcvbyte = (TextView) findViewById(R.id.rcvbyte);

        allhotunit = (TextView) findViewById(R.id.allhotunit);
        allflowunit = (TextView) findViewById(R.id.allflowunit);

        helptext = (TextView) findViewById(R.id.helptext);
        helptitle = (TextView) findViewById(R.id.helptitle);
        helptitle.setOnClickListener(helpFun);
    }

    private void clear_textDisplay() {
        sendtext.setText("");
        rcvtext.setText("");
        rcvbyte.setText("");

        startTimer(TI);
    }

    /**
     * 帮助按键响应事件
     */
    View.OnClickListener helpFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            helpFlag = helpFlag ^ 1;

            if (helpFlag == 0)
                helptext.setText("例:累计热量00000161 kwh" + "\n"
                        + "则:00~40的表=16.1 kwh,50~100的表=161 kwh,以此类推,累计流量相同");
            else
                helptext.setText("");
        }
    };

    /**
     * 读取数据按键响应事件
     */
    View.OnClickListener readbtnFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();


            inWhichAc = "runa.SetDataActivity.read";
            //获取完整的发送sendbyte[]
            String meterNumStr = nownum.getText().toString();
            byte[] sendbyte = SendDataAnalysis.ReadMeterSendByte(readmeter, meterNumStr, 5, 3);//5：表号起始位置，3：报文校验和起始位置
            //显示发送报文
            sendtext.setText(byteToHexString(sendbyte));
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(sendbyte);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    TcpSocket.receServerMessage();
//                }
//            },3000);

        }
    };
    /**
     * 设置数据按键响应事件
     */
    View.OnClickListener setdbtnFun = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();
            inWhichAc = "runa.SetDataActivity.set";
            set_BaoWen();

            byte[] sendbyte = SendDataAnalysis.setDataByte(setData);
            //显示发送报文
            sendtext.setText(byteToHexString(sendbyte));
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(sendbyte);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    TcpSocket.receServerMessage();
//                }
//            },3000);
        }
    };


    private void set_BaoWen() {
        //1
        String nownumStr = nownum.getText().toString();
        nownumStr.replace(".", "");
        String allhotStr = allhot.getText().toString();
        allhotStr.replace(".", "");
        String allflowStr = allflow.getText().toString();
        allflowStr.replace(".", "");
        String alltimeStr = alltime.getText().toString();
        alltimeStr.replace(".", "");
        String allhotunitStr = allhotunit.getText().toString();
        //2
        if (allhotunitStr == "GJ") {
            int allhotInt = Integer.parseInt(allhotStr);
            allhotInt = ((allhotInt * 10000) / 36);
            allhotStr = String.valueOf(allhotInt);
        }
        //3
        nownumStr = "00000000" + nownumStr;
        nownumStr = nownumStr.substring(nownumStr.length() - 8, nownumStr.length());
        allhotStr = "00000000" + allhotStr;
        allhotStr = allhotStr.substring(allhotStr.length() - 8, allhotStr.length());
        allflowStr = "00000000" + allflowStr;
        allflowStr = allflowStr.substring(allflowStr.length() - 8, allflowStr.length());
        alltimeStr = "00000000" + alltimeStr;
        alltimeStr = alltimeStr.substring(alltimeStr.length() - 8, alltimeStr.length());

        if (nownum.getText().toString().length() == 8) {
            setData[10] = (byte) ((nownumStr.charAt(0) - 0x30) * 16 + (nownumStr.charAt(1) - 0x30));
            setData[9] = (byte) ((nownumStr.charAt(2) - 0x30) * 16 + (nownumStr.charAt(3) - 0x30));
            setData[8] = (byte) ((nownumStr.charAt(4) - 0x30) * 16 + (nownumStr.charAt(5) - 0x30));
            setData[7] = (byte) ((nownumStr.charAt(6) - 0x30) * 16 + (nownumStr.charAt(7) - 0x30));
            setData[11] = 0x00;
            setData[12] = 0x11;
            setData[13] = 0x11;
        } else {
            for (int i = 0; i < 7; i++) {
                setData[11] = (byte) 0xAA;
            }
        }


        setData[21] = (byte) ((allhotStr.charAt(0) - 0x30) * 16 + (allhotStr.charAt(1) - 0x30));
        setData[20] = (byte) ((allhotStr.charAt(2) - 0x30) * 16 + (allhotStr.charAt(3) - 0x30));
        setData[23] = (byte) ((allhotStr.charAt(4) - 0x30) * 16 + (allhotStr.charAt(5) - 0x30));
        setData[22] = (byte) ((allhotStr.charAt(6) - 0x30) * 16 + (allhotStr.charAt(7) - 0x30));

        setData[29] = (byte) ((allflowStr.charAt(0) - 0x30) * 16 + (allflowStr.charAt(1) - 0x30));
        setData[28] = (byte) ((allflowStr.charAt(2) - 0x30) * 16 + (allflowStr.charAt(3) - 0x30));
        setData[31] = (byte) ((allflowStr.charAt(4) - 0x30) * 16 + (allflowStr.charAt(5) - 0x30));
        setData[30] = (byte) ((allflowStr.charAt(6) - 0x30) * 16 + (allflowStr.charAt(7) - 0x30));

        setData[32] = (byte) ((alltimeStr.charAt(2) - 0x30) * 16 + (alltimeStr.charAt(3) - 0x30));
        setData[35] = (byte) ((alltimeStr.charAt(4) - 0x30) * 16 + (alltimeStr.charAt(5) - 0x30));
        setData[34] = (byte) ((alltimeStr.charAt(6) - 0x30) * 16 + (alltimeStr.charAt(7) - 0x30));
    }

    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     *
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult = TcpSocket.readConnect();
        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        } else {
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }

    private MenuItem me;
    private int t_type = 0;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me = item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()) {
            case R.id.menu_connect:
                String connectResult = TcpSocket.wificonnect();//wifi connect
                show(connectResult);//TOast connect result
                if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                } else {
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            t_type = 1;
                        }
                    }, 1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(SetDataActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                t_type=0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (isWifi()) {
                    if (me != null) {
                        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {

                            me.setTitle("connect!");
                            me.setIcon(R.drawable.wifi_connect);
                        } else {

                            me.setTitle("no connect!");
                            me.setIcon(R.drawable.wifi_noconnect);
                        }
                    }
                } else {
                    if (me!=null){
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }

                }
            }
        });
    }

    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
